package com.mamingchao.foundation.QuestionPool;

import java.util.Arrays;

/**
 * 给定一个长度为m的字符串aim，和一个长度为n的字符串str；问能否再str中找到一个长度为m的连续字串，使得这个字串刚好由aim的m个字符组成，顺序无所谓。

 * 返回任意满足条件的字串的起始位置，如果没找到返回-1
 * Created by mamingchao on 2020/11/24.
 */
public class ContainChars {

    private static int findStr(String source, String target){

        if ("".equals(source) || "".equals(target)) {
            return -1;
        }

        int m = target.length();

        for (int i = 0; i < source.length() - m + 1; i++) {
            String temp = source.substring(i,i+m);
            boolean result = containSameChars(temp,target);
            if (result){
                return i;
            }
        }

        return -1;
    }


    
    private static boolean containSameChars(String source, String target){
        if ("".equals(source) || "".equals(target)) {
            return false;
        }

        if (source.length() != target.length()) {
            return false;
        }


        char[] sources = source.toCharArray();
        char[] targes = target.toCharArray();

        Arrays.sort(sources);
        Arrays.sort(targes);

        for (int i = 0; i < sources.length; i++) {
            if (sources[i] != targes[i]) {
                return false;
            }
        }

        return true;

    }

    public static void main(String[] args) {
//        System.out.println(containSameChars("abbc","bcaa"));

        String source = "abbacdcab";
        String target = "dacc";

        System.out.println(findStr(source,target));

    }

}
